package com.snda.sc;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.snda.sc.config.Configurable;
import com.snda.sc.config.IConfigRegistry;

@Component("autoConfigProcessor")
public class AutoConfigProcessor implements BeanPostProcessor, ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof IConfigRegistry) {
			for (Configurable config : applicationContext.getBeansOfType(Configurable.class).values())
				((IConfigRegistry) bean).registerConfig(config);
		}
		return bean;
	}
}
